package com.musicstore.web.controller;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.musicstore.biz.AlbumBiz;
import com.musicstore.biz.GenreBiz;
import com.musicstore.biz.ShoppingCartBiz;
import com.musicstore.entity.AlbumEntity;
import com.musicstore.entity.GenreEntity;
import com.musicstore.entity.ShoppingCart;
import com.musicstore.entity.UserEntity;

@Controller
public class AddCartController {
	@Autowired
	private ShoppingCartBiz shoppingCartBiz;
	@Autowired
	private AlbumBiz albumBiz;
	@Autowired
	private GenreBiz genreBiz;
	@RequestMapping("/addCart")
	public String AddCart(Model model,Integer id,HttpSession  session ,HttpServletRequest request,String title,Integer pageNo){
		UserEntity user = (UserEntity) session.getAttribute("user");
		if(user!=null){//判断用户是否登录了
			ShoppingCart cart=(ShoppingCart) request.getSession().getAttribute("cart");
			if(cart==null) //用户进入购物车
			{
				cart=new ShoppingCart();			
			}
			//商品添加购物车
			try {
				shoppingCartBiz.addCartItem(cart, id);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			pageNo=(pageNo==null)?1:pageNo;
	  		int pageSize =5;
			int startIndex = (pageNo-1)*pageSize;
			//保存购物车到session
			request.getSession().setAttribute("cart",cart);
			List<AlbumEntity> albumlist = albumBiz.getAlbumTitle(title, startIndex, pageSize);
			model.addAttribute("albumlist",albumlist);
		}else{
			model.addAttribute("error", "请先登录！");
		}
		return "shopping";
	}
}
